package com.hemerasolutions.v2trainer.dao;


import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.hemerasolutions.v2trainer.dao.interfaces.UserDaoInterface;
import com.hemerasolutions.v2trainer.model.users.User;
import com.hemerasolutions.v2trainer.model.users.User_;


@Repository(value = "userDao")
public class UserDao extends BaseDao<User> implements UserDaoInterface{
	private static final long serialVersionUID = 1L;

	@Override
	public User findByUserName(String userName) {
	
    	CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
		CriteriaQuery<User> cq  = cb.createQuery(User.class);
		Root<User> user = cq.from(User.class);
		Predicate pred;

		pred = cb.like(cb.upper(user.<String>get(User_.email)),userName);

		cq.where(pred);
		
	    return super.getEntityManager().createQuery(cq).getSingleResult();			

	    
	}

	public <Y> Y getActiveUser(User activeUser, Class<Y> type){

    	CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
		CriteriaQuery<Y> cq  = cb.createQuery(type);
		Root<Y> actor = cq.from(type);
		Join<Y,User> userActor = actor.join("user",JoinType.LEFT); 

		Predicate pred;
		
		pred = cb.equal(userActor.get(User_.id), activeUser.getId());
		
		cq.select(actor);	
		cq.where(pred);
		
	    return super.getEntityManager().createQuery(cq).getSingleResult();		
		

	}	

}
